package com.venutech.gongan.api;

import com.baomidou.mybatisplus.plugins.Page;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import com.shihang.misc.date.DateTimeUtil;
import com.venutech.gongan.common.Constants;
import com.venutech.gongan.entity.DictData;
import com.venutech.gongan.entity.Log;
import com.venutech.gongan.entity.QRCode;
import com.venutech.gongan.model.ResultFormat;
import com.venutech.gongan.payload.QrCodeListQueryPayload;
import com.venutech.gongan.service.AuditLogService;
import com.venutech.gongan.service.DictDataService;
import com.venutech.gongan.service.QRCodeService;
import com.venutech.gongan.util.FileUtils;
import com.venutech.gongan.util.ResultUtil;
import com.venutech.gongan.vo.QrCodeListQueryVO;
import com.venutech.gongan.vo.QrCodeOption;
import com.venutech.gongan.vo.QrCodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Api(value = "二维码相关的接口", tags = "二维码")
@RestController
@RequestMapping("qrCode")
@Slf4j
public class QrCodeController extends AbstractControllerBase {
    @Autowired
    private QRCodeService qrCodeService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private AuditLogService auditLogService;

    @Autowired
    private DictDataService dictDataService;


    @Value("${qrcode.save-dir}")
    String qrCodeSaveDir;

    @Value("${qrcode.path-mapping}")
    String qrCodePathMapping;

    @ApiOperation("获取所有二维码列表")
    @PostMapping("list")
    public QrCodeListQueryVO qrCodeList(@Validated @RequestBody QrCodeListQueryPayload payload) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        log.info("HttpSession 用户ID:  " + loginUser.getUserId());
        Integer type = Optional.ofNullable(payload.getType()).orElse(0);
        Page<QRCode> p = qrCodeService.getInfo(payload.getPage(), payload.getLimit(), payload.getBeginTime(), payload.getEndTime(), payload.getBadw(), payload.getQrId());

        if (type == 1) {
            eventThreadPool.execute(() -> {
                try {
                    String message = String.format("二维码查询：条形码编码Id %s", payload.getQrId());
                    int logId = rzLogService.addRzLog(loginUser.getUserId().intValue(), Constants.QUERY, message, Constants.LOG_OK, Constants.BACK);
                    String opCondition = String.format("qr_id=%s", payload.getQrId());
                    SysDept sysDept = sysDeptService.selectDeptById(loginUser.getDeptId());
                    SysUser currentUser = sysUserService.selectUserById(loginUser.getUserId());
                    auditLogService.logAudit(loginUser.getUsername(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                            currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
                            opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
                } catch (Exception ex) {
                    log.warn("QrCodeController.qrcode_list(): 日志记录异常， ex=", ex);
                }
            });
        }
        return new QrCodeListQueryVO("0", p.getTotal(), p.getRecords());
    }



    @ApiOperation("删除二维码")
    @DeleteMapping("/{id}")
    @ResponseBody
    public Integer qrcodeDelete(@PathVariable("id") String qr_id) {
        // User currentUser = oauthContext.getCurrentUser();
        //日志对象
        QRCode qrCode = qrCodeService.getById(Integer.parseInt(qr_id));
        int i = qrCodeService.deleteById(Integer.parseInt(qr_id));
        if (i > 0) {
            eventThreadPool.execute(()->{
                try {
                    String message = String.format("删除二维码, 二维码Id=%s, 二维码编码=%s", qr_id, qrCode.getQr_bm());
//                    int logId= rzLogService.addRzLog(currentUser.getUser_id(), Constants.DELETE, message, Constants.LOG_OK, Constants.BACK);
//                    String opCondition = String.format("qr_id=%s", qr_id);
//                    auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                            currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                            opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
                }catch (Exception ex){
                    log.warn("QrCodeController.qrcodeDelete(): 日志记录异常， ex=", ex);
                }
            });
            //代表正常
            return 0;
        } else {
            eventThreadPool.execute(()->{
                try {
                    String message = String.format("删除二维码, 二维码Id=%d, 二维码编码=%s", qrCode.getQr_id(), qrCode.getQr_bm());
//                    int logId= rzLogService.addRzLog(currentUser.getUser_id(), Constants.DELETE, message, Constants.LOG_OK, Constants.BACK);
//                    String opCondition = String.format("qr_id=%s", qr_id);
//                    auditLogService.logAudit(currentUser.getLogin_user_name(), currentUser.getNick_name(), currentUser.getEmployee_no(),
//                            currentUser.getId_No(), currentUser.getWork_unit_Name(), currentUser.getWork_unit_Code(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
//                            opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
                }catch (Exception ex){
                    log.warn("QrCodeController.qrcodeDelete(): 日志记录异常， ex=", ex);
                }
            });
            //代表异常
            return -1;
        }

    }



    @ApiOperation("下载二维码")
    @GetMapping("/downloadImage/{qrId}")
    public void downloadImage(HttpServletResponse response,
                              @PathVariable("qrId") String qr_id) {
        QRCode qrCode = qrCodeService.getById(Integer.parseInt(qr_id));
        //判断文件是否存在
        String filePath = String.format("%s%s", qrCodeSaveDir, qrCode.getQr_codeImgFileSaveDir());
        File files = new File(filePath);
        boolean flag = files.exists();
//        String path=qrCode.getQr_codeImgFileSaveDir();
        log.info(filePath + "  " + qr_id + "  " + flag);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser currentUser = sysUserService.selectUserById(loginUser.getUserId());
        if (flag) {
            Log newLog =new Log();
            newLog.setCzlx(Constants.DOWN);
            try {
                //根据文件路径下载文件信息
                FileUtils.down(response, filePath);
                response.setContentType("text/html;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                newLog.setCzlx(Constants.DOWN);
                eventThreadPool.execute(()->{
                    try {
                        String message = String.format("下载二维码, 二维码Id=%d, 二维码编码=%s", qrCode.getQr_id(), qrCode.getQr_bm());

                        int logId= rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.DOWN, message, Constants.LOG_OK, Constants.BACK);
                        String opCondition = String.format("qr_id=%s", qr_id);
                        auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                                currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
                                opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
                    }catch (Exception ex){
                        log.warn("QrCodeController.downLoadImage(): 日志记录异常， ex=", ex);
                    }
                });
            } catch (IOException e) {
                e.printStackTrace();

            }

        } else {
            try {
                response.setContentType("text/html;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println("图片不存在下载失败！<a href=\"javascript:history.go(-1)\">返回</a>");
            } catch (IOException e) {
                log.info("图片不存在无法下载失败！" + e);
            }

        }

        eventThreadPool.execute(() -> {
            try {
                String message = String.format("下载二维码, 二维码Id=%d, 二维码编码=%s", qrCode.getQr_id(), qrCode.getQr_bm());
                int logId = rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);

                String opCondition = String.format("qr_id=%s", qr_id);
                auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch(Exception ex) {
                log.warn("QrCodeController.downLoadImage(): 日志记录异常， ex=", ex);
            }
        });
    }

    @ApiOperation("批量下载二维码")
    @GetMapping("downloadUnZip")
    public void downloadUnZip(HttpServletResponse response, @RequestParam String ids) throws IOException {
        String[] array=ids.split(",");
        List<String> downLoadQrcodDir=new ArrayList<>();
        for(String k:array){
            log.info("downLoadUnZip:二维码批量下载,k={},qrCodeSaveDir={}",k,qrCodeSaveDir);
            QRCode qrCode = qrCodeService.getById(Integer.parseInt(k));
            if (Objects.isNull(qrCode)) {
                continue;
            }
            String filePath = String.format("%s%s", qrCodeSaveDir, qrCode.getQr_codeImgFileSaveDir());
            log.info("downLoadUnZip,二维码批量下载:filePath={}",filePath);
            downLoadQrcodDir.add(filePath);//获取要批量下载的二维码路径并保存到List集合中
        }
        log.info("downLoadUnZip:downLoadQrcodDir={}",downLoadQrcodDir);
        FileUtils.downLoadZip(qrCodeSaveDir, response,downLoadQrcodDir);

        eventThreadPool.execute(() -> {
            try {
                String message = String.format("批量下载二维码");
                SysUser currentUser = currentUser();
                int logId = rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.VIEW, message, Constants.LOG_OK, Constants.BACK);

                String opCondition = String.format("qr_id in (%s)", ids);
                auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_QUERY,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch(Exception ex) {
                log.warn("QrCodeController.downLoadUnZip(): 日志记录异常， ex=", ex);
            }
        });
    }

    @ApiOperation("页面搜索选项")
    @GetMapping("options")
    public QrCodeOption qrCodeOptions() {

        //区域编码
        List<DictData> list = dictDataService.getSelQybm();
        List<DictData> listqybm = new ArrayList<>();
        for (DictData data : list) {
            if (!data.getDict_label().equals("姑苏区")) {
                listqybm.add(data);
            }
        }
        //小类编码
        List<DictData> listxlbm = dictDataService.getSelXlbm();

        return new QrCodeOption(listqybm, listxlbm);
    }

    @ApiOperation("查看二维码详情")
    @GetMapping("detail/{id}")
    public QrCodeVO qrCodeDetail(@PathVariable("id") Integer qrId) {
        QRCode qrCode = qrCodeService.getById(qrId);
        QrCodeVO vo = new QrCodeVO();
        BeanUtils.copyProperties(qrCode, vo);
        //给图片src赋予新的地址
        String mappingPath = String.format("%s%s", qrCodePathMapping, qrCode.getQr_codeImgFileSaveDir());
        vo.setNewSrc(mappingPath);
        return vo;
    }


    @ApiOperation(value = "二维码修改")
    @PostMapping(value = "update/{id}")
    @ResponseBody
    public ResultFormat qrCodeUpdate(@PathVariable("id") Integer qr_id,
                             @RequestParam(name = "qybm", required = false) String qybm,
                             @RequestParam(name = "xlxbm", required = false) String xlxbm,
                             @RequestParam(name = "xh", required = false) String xh) {

        //二维码对象
        QRCode qrCode = qrCodeService.getById(qr_id);
//        qrCode.setQr_id(Integer.parseInt(qr_id));
        qrCode.setQybm(qybm);
        qrCode.setXlxbm(xlxbm);
        qrCode.setXh(xh);
        qrCode.setQr_bm(qybm + "-" + xlxbm + "-" + xh);
        qrCodeService.updateQRCode(qrCode);


        eventThreadPool.execute(() -> {
            try {
                String message = String.format("更新二维码：　二维码id=%d, 二维码编码=%s", qrCode.getQr_id(), qrCode.getQr_bm());
                SysUser currentUser = currentUser();
                int logId = rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.UPDATE, message, Constants.LOG_OK, Constants.BACK);

                String opCondition = String.format("qr_id=%d", qr_id);
                auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_UPDATE,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch(Exception ex) {
                log.warn("QrCodeController.qrCodeUpdate(): 日志记录异常， ex=", ex);
            }
        });

        return ResultUtil.success();
    }

    //单个背景图+二维码生成
    // xh: 前端传来的序号
    @ApiOperation(value = "二维码单个背景图+二维码生成")
    @PostMapping(value = "save")
    public ResultFormat qrcodeSave(@RequestParam(name = "qybm", required = false) String qybm,
                                   @RequestParam(name = "xlxbm", required = false) String xlxbm,
                                   @RequestParam(name = "xh", required = false) String xh) throws Exception {
        Integer xhInt = qrCodeService.getLastSeq();
        int qr_id = qrCodeService.createQrCodeWithFile("" + xhInt, qybm, xlxbm);
        log.info("成功生成二维码! qrid={},xlxbm={},qybm={}", qr_id,xlxbm,qybm);

        eventThreadPool.execute(() -> {
            try {
                QRCode qrCode = qrCodeService.getById(qr_id);
                String message = String.format("生成二维码：　二维码id=%d, 二维码编码=%s", qrCode.getQr_id(), qrCode.getQr_bm());
                SysUser currentUser = currentUser();
                int logId = rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.INSERT, message, Constants.LOG_OK, Constants.BACK);

                String opCondition = String.format("qr_id=%d", qr_id);
                auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_ADD,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch(Exception ex) {
                log.warn("QrCodeController.qrcodeSave(): 日志记录异常， ex=", ex);
            }
        });

        return ResultUtil.success("success");
    }

    //二维码批量生成
    @ApiOperation(value = "二维码批量生成")
    @PostMapping(value = "batchSave")
    @ResponseBody
    public Map<String, Object> qrcodeBatchSave(@RequestParam("number") String number,
                                               @RequestParam("qybm") String qybm,
                                               @RequestParam("xlxbm") String xlxbm)throws Exception {
        Map<String, Object> result = new HashMap<>();
        int count = Integer.parseInt(number);
        int j;
        for (j = 0; j < count ; j++) {
            try {
                int eightSeq = qrCodeService.getEightSeq();
                log.info("批量生成二维码中... {} of 2, eightSeq={}", j+1, eightSeq);
                int qr_id = qrCodeService.createQrCodeWithFile(String.valueOf(eightSeq),qybm,xlxbm);
                log.info("二维码生成完毕. qrId={}", qr_id);
            } catch (Exception e) {
                log.error("发生错误， 错误信息是：{}！", e);
            }
        }
        eventThreadPool.execute(() -> {
            try {
                String message = String.format("批量生成二维码：　二维码数量：", number);
                SysUser currentUser = currentUser();
                int logId = rzLogService.addRzLog(currentUser.getUserId().intValue(), Constants.INSERT, message, Constants.LOG_OK, Constants.BACK);

                String opCondition = String.format("number=%d", number);
                auditLogService.logAudit(currentUser.getUserName(), currentUser.getNickName(), currentUser.getEmployeeNo(),
                        currentUser.getIdNo(), currentUser.getWorkUnitName(), currentUser.getWorkUnitCode(), Constants.AUDIT_LOG_OP_TYPE_ADD,
                        opCondition, DateTimeUtil.formatDate(new Date(), "yyyyMMddHHmmss"), "1", message, String.valueOf(logId));
            } catch(Exception ex) {
                log.warn("QrCodeController.qrcodeBatchSave(): 日志记录异常， ex=", ex);
            }
        });

        result.put("code", "0");
        result.put("msg", "成功");
        return result;
    }

}
